<?php
namespace backend\controllers;

use common\helpers\TStringHelper;
use Yii;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\Response;

/**
 * Site controller
 */
class CommonController extends Controller
{

    public $enableCsrfValidation = false;

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'upload-thumb' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * 文件上传
     */
    public function actionUploadThumb(){
        $dir = Yii::$app->request->get('dir');
        if (empty($dir)) $dir = 'thumb';
        $targetFolder = \Yii::$app->basePath.'/../upload/'.$dir.'/'.date('Ymd');
        $file = new \yii\helpers\FileHelper();
        $file->createDirectory($targetFolder);
        $isEvent = Yii::$app->request->get('event');
        $thumb = Yii::$app->request->get('thumb');//是否生成缩略图
        $type = Yii::$app->request->get('type');//上传类型
        if (!empty($_FILES)) {
            $tempFile = $_FILES['Filedata']['tmp_name'];
            $fileParts = pathinfo($_FILES['Filedata']['name']);
            $extension = strtolower($fileParts['extension']);
            $random = time() . rand(1000, 9999);
            $randName = $random . "." . $extension;
            $targetFile = rtrim($targetFolder,'/') . '/' . $randName;
            if ($type == 'video') {
                $fileTypes = array('ogg','mp4');
                if (!in_array($extension, $fileTypes)) {
                    $msg = [
                        'error' => 1,
                        'msg' => '上传格式错误，目前只支持mp4、ogg格式',
                    ];
                    echo json_encode($msg);
                    exit;
                }
            }elseif ($type == 'pdf') {
                $fileTypes = array('pdf');
                if (!in_array($extension, $fileTypes)) {
                    $msg = [
                        'error' => 1,
                        'msg' => '上传格式错误，目前只支持pdf格式',
                    ];
                    echo json_encode($msg);
                    exit;
                }
            }elseif ($type == 'excel') {
                $fileTypes = array('xlsx', 'xls');
                if (!in_array($extension, $fileTypes)) {
                    $msg = [
                        'error' => 1,
                        'msg' => '上传格式错误，目前只支持xlsx、xls格式',
                    ];
                    echo json_encode($msg);
                    exit;
                }
            }else{
                $fileTypes = array('jpg','jpeg','png','ogg','mp4');
                if (!in_array($extension, $fileTypes)) {
                    $msg = [
                        'error' => 1,
                        'msg' => '上传格式错误，目前只支持'.join('、', $fileTypes).'格式',
                    ];
                    echo json_encode($msg);
                    exit;
                }
            }
            $uploadfile_path = 'upload/'.$dir.'/'.date('Ymd').'/'.$randName;
            if ($isEvent == 1) {
                $callback['fileUrl'] = '/'.$uploadfile_path;
            }else{
                $callback['fileUrl'] = Yii::$app->request->hostInfo . '/' . $uploadfile_path;
            }
            $callback['filename'] = urlencode($fileParts['filename']);
            $callback['randName'] = $random;
            if (in_array(strtolower($fileParts['extension']),$fileTypes)) {
                move_uploaded_file($tempFile,$targetFile);
                //生成缩略图
                if (!empty($thumb)) {
                    $thumbArr = explode('|', $thumb);
                    foreach ($thumbArr as $val) {
                        list($width, $height) = explode(',', $val);
                        $suffix = '_' . str_replace(',', 'x', $val);
                        TStringHelper::imageCrop($targetFile, $width, $height, 'upload/' . $dir . '/' . date('Ymd'), $suffix);
                    }
                }
                echo urldecode(json_encode($callback));
            } else {
                $msg = [
                    'error' => 1,
                    'msg' => '不能上传后缀为'.$fileParts['extension'].'文件',
                ];
                echo json_encode($msg);
                exit;
            }
        }else{
            $msg = [
                'error' => 1,
                'msg' => '没有上传文件',
            ];
            echo json_encode($msg);
            exit;
        }
    }

    /**
     * ckeditor上传
     */
    public function actionUrl()
    {
        $targetFolder = \Yii::$app->basePath.'/../upload/file/'.date('Ymd');
        $file = new \yii\helpers\FileHelper();
        $file->createDirectory($targetFolder);
        $isEvent = Yii::$app->request->get('event');
        if (!empty($_FILES)) {
            $tempFile = $_FILES['upload']['tmp_name'];
            $fileParts = pathinfo($_FILES['upload']['name']);
            $extension = $fileParts['extension'];
            $random = time() . rand(1000, 9999);
            $randName = $random . "." . $extension;
            $targetFile = rtrim($targetFolder,'/') . '/' . $randName;
            $fileTypes = array(
                'jpg',
                'jpeg',
                'png',
                'pjpeg',
                'gif',
                'bmp',
                'x-png');
            $uploadfile_path = 'upload/file/'.date('Ymd').'/'.$randName;
            if ($isEvent == 1) {
                $url = '/'.$uploadfile_path;
            }else{
                $url = Yii::$app->request->hostInfo . '/' . $uploadfile_path;
            }
            if (in_array($fileParts['extension'],$fileTypes)) {
                move_uploaded_file($tempFile,$targetFile);
                $message = '';
            } else {
                $url = '';
                $message = '不能上传后缀为'.$fileParts['extension'].'文件';
            }
        }else{
            $url = '';
            $message = "没有上传文件";
        }
        $funcNum = $_GET['CKEditorFuncNum'] ;
        echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($funcNum, '$url', '$message');</script>";
    }

    /**
     * 弹出地图选择
     * @return string
     */
    public function actionMap(){
//        Yii::$app->response->format = Response::FORMAT_JSON;
        $lat = Yii::$app->request->get('lat');//纬度
        $lng = Yii::$app->request->get('lng');//经度

        return $this->renderAjax('map', [
            'lat' => $lat,
            'lng' => $lng
        ]);

    }
}
